// index.js

var common = require('../../utils/userstatus');
var util = require('../../utils/util');


Component({
  data: {
    userInfo: "",
    appInstance: "",
    shareId: ""
  },
  methods: {
    onLoad() {
      var appInstance = getApp();
      this.data.appInstance = appInstance;
    },
    onShow() {
      var userInfo = wx.getStorageSync('userInfo') || "";

      this.setData({
        userInfo: userInfo
      })
    },
   onShareAppMessage() {
      var path = '/pages/login/login';
      console.log(path)
      return {
        title: "分享小程序",
        path: path,
        imageUrl: '../../images/index/youkongma.jpg'
      }
    },
    // addPerson() {
    //   var code = util.getRandomCode(10);
    //   this.data.shareId = code;
    //   console.log("随机数" + this.data.shareId)
    //   wx.showShareMenu({
    //     withShareTicket: true,
    //     menus: ['shareAppMessage'],
    //     complete: () => {
    //       console.log("分享成功")
    //       this.getShareUid();
    //     }
    //   })

    // },
    // onShareAppMessage() {
    //   var id = wx.getStorageSync('userInfo').id;
    //   var code = this.data.shareId;
    //   var path = '/pages/share/share?id=' + id +
    //     '&code=' + code;
    //   console.log(path)
    //   return {
    //     title: "分享添加好友",
    //     path: path,
    //     imageUrl: '../../images/index/youkongma.jpg'
    //   }
    // },
    getInfo() {
      var userInfo = this.data.userInfo;
      wx.navigateTo({
        url: '/pages/info/info',
        events: {
          //回显更新数据
          backShow: (data) => {
            console.log(data)
            this.setData({
              userInfo: data.data
            })
          }
        },
        success: function (res) {
          userInfo.flag = true;
          res.eventChannel.emit('infoData', {
            data: userInfo
          })
        }
      })
    },
    // getShareUid() {
    //   var url = '/applet/getShareUid';

    //   var id = wx.getStorageSync('userInfo').id;
    //   var data = {
    //     id: id,
    //     code: this.data.shareId
    //   }
    //   if (this.data.shareId) {
    //     util.postRequest(url, data)
    //   }
    // },
    getPhoneNumber(e) {
      console.log(e.detail.code) // 动态令牌
      console.log(e.detail.errMsg) // 回调信息（成功失败都会返回）
      console.log(e.detail.errno)
      var code = e.detail.code;
      if (code) {
        wx.showLoading();
        var url = '/applet/getPhoneNumber';
        util.postRequest(url, {
          id: wx.getStorageSync('userInfo').id,
          code: code
        }, (data) => {
          wx.hideLoading();
          if (data.code == 2000) {
            var phoneNumber = data.data.phoneNumber;
            if (phoneNumber) {
              var userInfo = wx.getStorageSync('userInfo');
              userInfo.phoneNumber = phoneNumber;
              wx.setStorageSync('userInfo', userInfo)
              this.setData({
                userInfo: userInfo
              })
            }
            wx.showToast({
              title: '成功！',
              icon: 'error',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: '获取失败',
              icon: 'error',
              duration: 2000
            })
          }
        }, error => {
          wx.hideLoading();
          wx.showToast({
            title: '获取失败',
            icon: 'error',
            duration: 2000
          })

        })
      }
    },
    subscribeTap() {
      wx.requestSubscribeMessage({
        tmplIds: ['qH1fy2q_cnQN6IUU6pkxV9TvW8YtEVzdfiGgkFxb-_A'],
        success: (res) => {
          if (res.errMsg === "requestSubscribeMessage:ok") {
            wx.showToast({
              title: '订阅成功',
              icon: 'error',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: '订阅失败',
              icon: 'error',
              duration: 2000
            })
          }

        },
        fail: (err) => {
          wx.showToast({
            title: '订阅失败',
            icon: 'error',
            duration: 2000
          })
        }
      })
    },
    loginOut() {
      wx.showModal({
        title: '提示',
        content: '确定要退出吗',
        success(res) {
          if (res.confirm) {
            util.clearHeartBeatInterval();
            util.postRequest("/applet/loginOut", {
              id: wx.getStorageSync('userInfo').id
            }, (data) => {
              wx.clearStorageSync();
              wx.redirectTo({
                url: '/pages/login/login'
              })
              //如果主动退出则不自动登录
              wx.setStorageSync('autoLogin', "1")
            }, (error) => {
              wx.clearStorageSync();
              wx.redirectTo({
                url: '/pages/login/login'
              })
              //如果主动退出则不自动登录
              wx.setStorageSync('autoLogin', "1")
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    },
    updateUsername() {
      var username = this.data.userInfo.username;
      var obj = {
        title: "名字",
        length: 10,
        data: username,
        key: "username"
      }
      wx.navigateTo({
        url: '/pages/inputinfo/inputinfo',
        events: {
          backShow: (data) => {
            console.log(data)
            this.setData({
              'userInfo.username': data.data.username
            })
          }
        },
        success: (res) => {
          res.eventChannel.emit('infoData', {
            data: obj
          })
        },
        fail: function (error) {
          console.log(error)
        }
      })
    },
    updatePhoneNumber() {
      var phoneNumber = this.data.userInfo.phoneNumber;
      var obj = {
        title: "手机号码",
        length: 12,
        data: phoneNumber,
        key: "phoneNumber"
      }
      wx.navigateTo({
        url: '/pages/inputinfo/inputinfo',
        events: {
          backShow: (data) => {
            console.log(data)
            this.setData({
              'userInfo.phoneNumber': data.data.phoneNumber
            })
          }
        },
        success: (res) => {
          res.eventChannel.emit('infoData', {
            data: obj
          })
        },
        fail: function (error) {
          console.log(error)
        }
      })
    },
    updateSign() {
      var sign = this.data.userInfo.sign;
      var obj = {
        title: "个性签名",
        length: 30,
        data: sign,
        key: "sign"
      }
      wx.navigateTo({
        url: '/pages/inputinfo/inputinfo',
        events: {
          backShow: (data) => {
            console.log(data)
            this.setData({
              'userInfo.sign': data.data.sign
            })
          }
        },
        success: (res) => {
          res.eventChannel.emit('infoData', {
            data: obj
          })
        },
        fail: function (error) {
          console.log(error)
        }
      })
    },
    updateuserStatus() {
      // var flag = this.data.userInfo.flag;
      // if (!flag) {
      //   return;
      // }
      var userStatusStr = this.data.userInfo.userStatusStr;
      wx.navigateTo({
        url: '/pages/status/status',
        events: {
          backShow: (data) => {
            this.setData({
              'userInfo.userStatusStr': data.data.userStatusStr
            })
          }
        },
        success: function (res) {
          res.eventChannel.emit('infoData', {
            data: userStatusStr
          })
        },
        fail: function (error) {
          console.log(error)
        }
      })
    },
    updateUserProfile() {
      var that = this;
      wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album', 'camera'],
        maxDuration: 30,
        camera: 'back',
        success(res) {
          console.log(res.tempFiles[0].tempFilePath)
          var size = res.tempFiles[0].size;
          if (size / 1048576 > 8) {
            wx.showToast({
              title: '最大不超过8M',
              icon: 'error',
              duration: 2000
            })
            return;
          }
          wx.cropImage({
            src: res.tempFiles[0].tempFilePath, // 图片路径
            cropScale: '1:1', // 裁剪比例
            success(res) {
              //todo 这里先上传到后台
              var tempFilePath = res.tempFilePath;
              var url = '/applet/uploadProfileImage';
              util.uploadFile(url,
                tempFilePath, {
                  userId: wx.getStorageSync('userInfo').id
                },
                (data) => {
                  var jsonData = JSON.parse(data);
                  console.log(jsonData)
                  if (jsonData.code === 2000) {
                    var userInfo = wx.getStorageSync('userInfo');
                    userInfo.profileImagePath = util.backServerUrl +
                      jsonData.data.profileImagePath;
                    wx.setStorageSync('userInfo', userInfo)
                    that.setData({
                      userInfo: userInfo
                    })
                  } else {
                    wx.showToast({
                      title: '修改失败',
                      icon: 'error',
                      duration: 2000
                    })
                  }
                },
                (error) => {})
            }
          })
        },
        fail(error) {

        }
      })
    },
    switchChange(event) {
      var value = event.detail.value;
      var switchValue;
      if (value) {
        switchValue = 1;
      } else {
        switchValue = 0;

      }
      var url = '/applet/updateUserInfo';
      util.postRequest(
        url, {
          id: this.data.userInfo.id,
          notificationSwitch: this.data.userInfo.notificationSwitch
        },
        (data) => {
          if (data.code == 2000) {
            wx.showToast({
              title: '修改成功',
              icon: 'sucess',
              duration: 2000
            })
            this.setData({
              'userInfo.notificationSwitch': switchValue
            });
          } else {
            this.setData({
              'userInfo.notificationSwitch': this.data.userInfo.notificationSwitch
            });
            wx.showToast({
              title: '修改失败',
              icon: 'error',
              duration: 2000
            })
          }
        },
        (error) => {
          this.setData({
            'userInfo.notificationSwitch': this.data.userInfo.notificationSwitch
          });
          wx.showToast({
            title: '修改失败',
            icon: 'error',
            duration: 2000
          })
        });
    }
  },
  pageLifetimes: {
    show() {
      if (typeof this.getTabBar === 'function' &&
        this.getTabBar()) {
        this.getTabBar().setData({
          selected: 1
        })
      }
    }
  },
})